
import React, { useMemo } from 'react';
import { Card, CardContent, CardHeader, CardTitle } from '@/components/ui/card';
import { Badge } from '@/components/ui/badge';
import { Tabs, TabsContent, TabsList, TabsTrigger } from "@/components/ui/tabs";
import { 
  Wrench, 
  Users, 
  TrendingUp,
  Truck 
} from 'lucide-react';
import {
  Table,
  TableBody,
  TableCell,
  TableHead,
  TableHeader,
  TableRow,
} from "@/components/ui/table";

export default function ResourceManager({ scheme }) {
  // 从施工步骤中汇总资源数据
  const aggregatedResources = useMemo(() => {
    const steps = scheme.constructionSteps || [];
    
    // 汇总物料
    const materialsMap = new Map();
    steps.forEach((step, stepIndex) => {
      (step.requiredMaterials || []).forEach(material => {
        const key = `${material.name}-${material.specification}`;
        if (materialsMap.has(key)) {
          const existing = materialsMap.get(key);
          materialsMap.set(key, {
            ...existing,
            quantity: existing.quantity + (material.quantity || 0),
            steps: [...existing.steps, stepIndex + 1]
          });
        } else {
          materialsMap.set(key, {
            ...material,
            steps: [stepIndex + 1]
          });
        }
      });
    });

    // 汇总人员（取峰值需求）
    const personnelMap = new Map();
    steps.forEach((step, stepIndex) => {
      (step.requiredPersonnel || []).forEach(person => {
        const key = `${person.role}`;
        if (personnelMap.has(key)) {
          const existing = personnelMap.get(key);
          // Only update if current step's quantity is higher than existing peak
          if ((person.quantity || 0) > existing.quantity) {
            personnelMap.set(key, {
              ...person,
              steps: [...existing.steps, stepIndex + 1] // Keep all steps where this peak occurred or was relevant
            });
          } else if ((person.quantity || 0) === existing.quantity) {
            // If quantity is the same, just add the step
            existing.steps.push(stepIndex + 1);
          }
          // If current quantity is lower, do nothing for quantity, just add step
          else {
            existing.steps.push(stepIndex + 1);
          }
        } else {
          personnelMap.set(key, {
            ...person,
            steps: [stepIndex + 1]
          });
        }
      });
    });

    // 新增：汇总工器具
    const equipmentMap = new Map();
    steps.forEach((step, stepIndex) => {
      (step.requiredEquipment || []).forEach(item => {
        const key = `${item.name}-${item.specification}`;
        if (equipmentMap.has(key)) {
          const existing = equipmentMap.get(key);
          equipmentMap.set(key, {
            ...existing,
            quantity: existing.quantity + (item.quantity || 0),
            steps: [...existing.steps, stepIndex + 1]
          });
        } else {
          equipmentMap.set(key, { ...item, steps: [stepIndex + 1] });
        }
      });
    });

    // 新增：汇总车辆（取峰值需求）
    const vehiclesMap = new Map();
    steps.forEach((step, stepIndex) => {
      (step.requiredVehicles || []).forEach(vehicle => {
        const key = vehicle.type;
        if (vehiclesMap.has(key)) {
          const existing = vehiclesMap.get(key);
          // Only update if current step's quantity is higher than existing peak
          if ((vehicle.quantity || 0) > existing.quantity) {
            vehiclesMap.set(key, { ...vehicle, steps: [...existing.steps, stepIndex + 1] });
          } else if ((vehicle.quantity || 0) === existing.quantity) {
            // If quantity is the same, just add the step
            existing.steps.push(stepIndex + 1);
          }
          // If current quantity is lower, do nothing for quantity, just add step
          else {
            existing.steps.push(stepIndex + 1);
          }
        } else {
          vehiclesMap.set(key, { ...vehicle, steps: [stepIndex + 1] });
        }
      });
    });

    return {
      materials: Array.from(materialsMap.values()),
      personnel: Array.from(personnelMap.values()),
      equipment: Array.from(equipmentMap.values()),
      vehicles: Array.from(vehiclesMap.values()),
    };
  }, [scheme.constructionSteps]);

  const totalManpowerDays = useMemo(() => {
    return aggregatedResources.personnel.reduce((sum, person) => {
      // Calculate person-days by multiplying quantity by estimated work days
      const estimatedWorkDays = scheme.totalDuration || 1; // Use total duration as default
      return sum + (person.quantity * estimatedWorkDays);
    }, 0);
  }, [aggregatedResources.personnel, scheme.totalDuration]);

  // The cost estimation section has been removed as per requirements.

  return (
    <Card>
      <CardHeader>
        <CardTitle className="flex items-center gap-2">
          资源分析汇总
        </CardTitle>
        <p className="text-sm text-gray-600">
          此页面展示从各施工步骤汇总的资源需求，如需修改请前往"施工步骤"页面编辑具体步骤
        </p>
      </CardHeader>
      
      <CardContent>
        {/* The cost overview section has been removed as per requirements */}

        <Tabs defaultValue="materials" className="w-full">
          <TabsList className="grid w-full grid-cols-4">
            <TabsTrigger value="materials" className="flex items-center gap-2">
              <Wrench className="w-4 h-4"/>
              物料 ({aggregatedResources.materials.length})
            </TabsTrigger>
            <TabsTrigger value="personnel" className="flex items-center gap-2">
              <Users className="w-4 h-4"/>
              人员 ({aggregatedResources.personnel.length})
            </TabsTrigger>
            <TabsTrigger value="equipment" className="flex items-center gap-2">
              <Wrench className="w-4 h-4"/>
              工器具 ({aggregatedResources.equipment.length})
            </TabsTrigger>
            <TabsTrigger value="vehicles" className="flex items-center gap-2">
              <Truck className="w-4 h-4"/>
              车辆 ({aggregatedResources.vehicles.length})
            </TabsTrigger>
          </TabsList>

          {/* 物料汇总 */}
          <TabsContent value="materials" className="mt-4">
            <div className="mb-4 flex items-center gap-2 text-sm text-blue-600">
              <TrendingUp className="w-4 h-4" />
              <span>以下数据从各施工步骤自动汇总而来</span>
            </div>
            
            {aggregatedResources.materials.length > 0 ? (
              <div className="border rounded-md overflow-hidden">
                <Table>
                  <TableHeader>
                    <TableRow>
                      <TableHead>物料名称</TableHead>
                      <TableHead>规格型号</TableHead>
                      <TableHead>单位</TableHead>
                      <TableHead>汇总数量</TableHead>
                      <TableHead>涉及步骤</TableHead>
                    </TableRow>
                  </TableHeader>
                  <TableBody>
                    {aggregatedResources.materials.map((material, index) => (
                      <TableRow key={index}>
                        <TableCell className="font-medium">{material.name}</TableCell>
                        <TableCell>{material.specification}</TableCell>
                        <TableCell>{material.unit}</TableCell>
                        <TableCell className="font-semibold text-blue-600">
                          {material.quantity}
                        </TableCell>
                        <TableCell>
                          <div className="flex gap-1">
                            {material.steps.map(stepNum => (
                              <Badge key={stepNum} variant="outline" className="text-xs">
                                步骤{stepNum}
                              </Badge>
                            ))}
                          </div>
                        </TableCell>
                      </TableRow>
                    ))}
                  </TableBody>
                </Table>
              </div>
            ) : (
              <div className="text-center py-8 text-gray-500 border border-dashed rounded-lg">
                <Wrench className="w-12 h-12 mx-auto mb-2 text-gray-300"/>
                <p>暂无物料需求</p>
                <p className="text-sm">请在"施工步骤"页面为各步骤添加物料需求</p>
              </div>
            )}
          </TabsContent>

          {/* 人员配置 */}
          <TabsContent value="personnel" className="mt-4">
            <div className="mb-4 flex items-center gap-2 text-sm text-blue-600">
              <TrendingUp className="w-4 h-4" />
              <span>显示各工种的峰值需求量</span>
            </div>
            
            {aggregatedResources.personnel.length > 0 ? (
              <div className="border rounded-md overflow-hidden">
                <Table>
                  <TableHeader>
                    <TableRow>
                      <TableHead>工种/岗位</TableHead>
                      <TableHead>峰值需求</TableHead>
                      <TableHead>资质要求</TableHead>
                      <TableHead>涉及步骤</TableHead>
                    </TableRow>
                  </TableHeader>
                  <TableBody>
                    {aggregatedResources.personnel.map((person, index) => (
                      <TableRow key={index}>
                        <TableCell className="font-medium">{person.role}</TableCell>
                        <TableCell className="font-semibold text-green-600">
                          {person.quantity} 人
                        </TableCell>
                        <TableCell>{person.qualification || '-'}</TableCell>
                        <TableCell>
                          <div className="flex gap-1">
                            {person.steps.map(stepNum => (
                              <Badge key={stepNum} variant="outline" className="text-xs">
                                步骤{stepNum}
                              </Badge>
                            ))}
                          </div>
                        </TableCell>
                      </TableRow>
                    ))}
                  </TableBody>
                </Table>
              </div>
            ) : (
              <div className="text-center py-8 text-gray-500 border border-dashed rounded-lg">
                <Users className="w-12 h-12 mx-auto mb-2 text-gray-300"/>
                <p>暂无人员配置</p>
                <p className="text-sm">请在"施工步骤"页面为各步骤添加人员需求</p>
              </div>
            )}
          </TabsContent>

          {/* 新增：工器具汇总 */}
          <TabsContent value="equipment" className="mt-4">
            <div className="mb-4 flex items-center gap-2 text-sm text-blue-600">
              <TrendingUp className="w-4 h-4" />
              <span>以下数据从各施工步骤自动汇总而来</span>
            </div>
            
            {aggregatedResources.equipment.length > 0 ? (
              <div className="border rounded-md overflow-hidden">
                <Table>
                  <TableHeader>
                    <TableRow>
                      <TableHead>工器具名称</TableHead>
                      <TableHead>规格型号</TableHead>
                      <TableHead>单位</TableHead>
                      <TableHead>汇总数量</TableHead>
                      <TableHead>涉及步骤</TableHead>
                    </TableRow>
                  </TableHeader>
                  <TableBody>
                    {aggregatedResources.equipment.map((item, index) => (
                      <TableRow key={index}>
                        <TableCell className="font-medium">{item.name}</TableCell>
                        <TableCell>{item.specification}</TableCell>
                        <TableCell>{item.unit}</TableCell>
                        <TableCell className="font-semibold text-orange-600">
                          {item.quantity}
                        </TableCell>
                        <TableCell>
                          <div className="flex gap-1">
                            {item.steps.map(stepNum => (
                              <Badge key={stepNum} variant="outline" className="text-xs">
                                步骤{stepNum}
                              </Badge>
                            ))}
                          </div>
                        </TableCell>
                      </TableRow>
                    ))}
                  </TableBody>
                </Table>
              </div>
            ) : (
              <div className="text-center py-8 text-gray-500 border border-dashed rounded-lg">
                <Wrench className="w-12 h-12 mx-auto mb-2 text-gray-300"/>
                <p>暂无工器具需求</p>
                <p className="text-sm">请在"施工步骤"页面为各步骤添加工器具需求</p>
              </div>
            )}
          </TabsContent>

          {/* 新增：车辆汇总 */}
          <TabsContent value="vehicles" className="mt-4">
            <div className="mb-4 flex items-center gap-2 text-sm text-blue-600">
              <TrendingUp className="w-4 h-4" />
              <span>显示各类型车辆的峰值需求量</span>
            </div>
            
            {aggregatedResources.vehicles.length > 0 ? (
              <div className="border rounded-md overflow-hidden">
                <Table>
                  <TableHeader>
                    <TableRow>
                      <TableHead>车辆类型</TableHead>
                      <TableHead>峰值需求</TableHead>
                      <TableHead>涉及步骤</TableHead>
                    </TableRow>
                  </TableHeader>
                  <TableBody>
                    {aggregatedResources.vehicles.map((vehicle, index) => (
                      <TableRow key={index}>
                        <TableCell className="font-medium">{vehicle.type}</TableCell>
                        <TableCell className="font-semibold text-teal-600">
                          {vehicle.quantity} 辆
                        </TableCell>
                        <TableCell>
                          <div className="flex gap-1">
                            {vehicle.steps.map(stepNum => (
                              <Badge key={stepNum} variant="outline" className="text-xs">
                                步骤{stepNum}
                              </Badge>
                            ))}
                          </div>
                        </TableCell>
                      </TableRow>
                    ))}
                  </TableBody>
                </Table>
              </div>
            ) : (
              <div className="text-center py-8 text-gray-500 border border-dashed rounded-lg">
                <Truck className="w-12 h-12 mx-auto mb-2 text-gray-300"/>
                <p>暂无车辆需求</p>
                <p className="text-sm">请在"施工步骤"页面为各步骤添加车辆需求</p>
              </div>
            )}
          </TabsContent>
        </Tabs>
      </CardContent>
    </Card>
  );
}
